import EventCenter from "../../lib/EventCenter";
import Sdk from "../../lib/Sdk";
import { TipManager } from "../../lib/TipManager";
import Utils from "../../lib/Utils";
import {ui} from "../../ui/layaMaxUI"
import EventEunm from "../data/EventEunm";
import PlayerData from "../data/PlayerData";
export default class BuyLiveDialog extends ui.BuyLiveDialogUI{
    private mGold:number=50;
    private mCd:number=0;
    onEnable(){
        this.goldBtn.on(Laya.Event.CLICK,this,this.glodClick);
        this.videoBtn.on(Laya.Event.CLICK,this,this.videoClick);
        this.closeBtn.once(Laya.Event.CLICK,this,this.close);
        this.goldBtn.getChildByName("goldTxt")["text"]=this.mGold+"";
        let ttime = new Date().getTime();
        let tpasstime = Math.floor((ttime-PlayerData.getIns().liveTime)/1000);
        if(tpasstime>=PlayerData.getIns().maxCd){
            tpasstime = tpasstime%PlayerData.getIns().maxCd;
            let times = Math.floor(tpasstime/PlayerData.getIns().maxCd);
            PlayerData.getIns().addLive(times);
        }
        this.mCd=PlayerData.getIns().maxCd-tpasstime;
        if(this.mCd>PlayerData.getIns().maxCd){
            this.mCd=PlayerData.getIns().maxCd;
            PlayerData.getIns().liveTime=ttime;
        }
        this.timer.loop(1000,this,this.update);
        this.fresh();
        Sdk.getIns().showBanner();
    }

    private update(){
        this.mCd--;
        if(this.mCd<=0){
            this.mCd==0;
            if(PlayerData.getIns().isMaxLive()){
                this.timer.clear(this,this.update);
            }else{
                PlayerData.getIns().addLive();
                this.mCd=PlayerData.getIns().maxCd;
            }
        }
        this.fresh();
    }

    private fresh(){
        this.cdTxt.text=Utils.timeToNor(this.mCd);
    }

    private glodClick(){
        if(PlayerData.getIns().gold>=this.mGold){
            PlayerData.getIns().addLive()
            PlayerData.getIns().addGold(-this.mGold);
            EventCenter.getIns().event(EventEunm.goldChange);
            EventCenter.getIns().event(EventEunm.liveChange);
            this.close();
        }else{
            TipManager.ins.showMsgAlert("金币不足",this);
        }
    }

    private videoClick(){
        Sdk.getIns().showAd((_code:number)=>{
            if(_code==0){
                PlayerData.getIns().addLive();
                EventCenter.getIns().event(EventEunm.liveChange);
                this.close();
            }else{
                TipManager.ins.showMsgAlert("观看完整视频才能获取奖励",this);
            }
        });
    }

    onDisable(){
        this.goldBtn.off(Laya.Event.CLICK,this,this.glodClick);
        this.videoBtn.off(Laya.Event.CLICK,this,this.videoClick);
        this.timer.clear(this,this.update);
        Sdk.getIns().hideBanner();
    }
}